import re
import sqlite3
import os
import logging
from django.http import HttpResponse
from django.conf import settings
import json
import shutil
import random
oozie_home='/export/datamarket/oozie/oozie-4.3.1/bin/'
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')

def terminateMission(request):

	if request.method == 'POST':
		try:	
			received_json_data=json.loads(request.body.decode().replace("'", "\""))
			logging.info("\n\n\n\t"+str(received_json_data)+"\n\n")
			jobid=received_json_data['jobid'].strip()
			
			db_path = os.path.normpath('/export/datamarket/OozieProperties/oozie_project/db.sqlite3') 
			db = sqlite3.connect(db_path) 
			# 通过cursor创建游标
			cursor = db.cursor()
			sql_jobid="select mission_val from oozie_configuration where jobid ={}".format(jobid)
			cursor.execute(sql_jobid)
			mission_val=cursor.fetchall()
			mission_val=mission_val[0][0]
			
			#通过oozie查找要终止的job的信息
			randomNum=os.popen('echo -n `date +%s%N`').read() 
			f=open('jobIDinfo'+str(randomNum)+str(random.uniform(1, 24)),'w')
			f2=open('jobid'+str(randomNum)+str(random.uniform(1, 24)),'w')
			jobIDinfoFile=re.findall(r"name='(.*?)'\s",str(f))[0]
			jobidFile=re.findall(r"name='(.*?)'\s",str(f))[0]
			os.system("oozie jobs -localtime -filter 'name={}' -len 1 > jobIDinfo".format(mission_val))
			os.system("cat jobIDinfo| awk -F ' ' '{print$1}' > jobid")
			os.system("sed -i '1d' jobid")
			os.system("sed -i '1d' jobid")
			os.system("sed -i '2d' jobid")
			jobid=os.popen("cat jobid").read().strip()
			os.system("cat jobIDinfo| awk -F ' ' '{print$3}' > jobid")
			os.system("sed -i '1d' jobid")
			status=os.popen("cat jobid").read().strip()
			os.remove("jobIDinfo")
			os.remove("jobid")
			cursor.close()
			db.commit()
			db.close()
			if status=='RUNNING':
				os.system(oozie_home+"oozie job -kill {}".format(jobid))
				
				
				result={"result":mission_val+"终止成功","code":"0"}
				logging.info(result)
				return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
			else:
				logging.info(mission_val+"没有运行/运行完成，无需终止")
				result2={"result":mission_val+"没有运行/运行完成，无需终止","code":"2"}
				return HttpResponse(json.dumps(result2,ensure_ascii=False), content_type="application/json;charset=utf-8")
		except:
			result={"result":"没有终止","code":"1"}
			logging.info(result)
			return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
	else:
		pass
